﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AGR.Services.Employee;
using AGR.Services.Employee.Contract;
using AGR.Services;
using AGR.Model;

namespace AGR.Web.Pages.Employees
{
    public partial class Employees : System.Web.UI.Page
    {
        private IEmployeeService _employeeService = new EmployeeService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ClearMessage();
                this.LoadGrid();
            }
        }

        #region Button Methods

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchBy = txtSearch.Text;

            if (string.IsNullOrEmpty(searchBy))
            {
                this.ShowMessage("Please enter a search parameter and try again.", SiteMaster.MessageType.Information);
                txtSearch.Focus();
                return;
            }

            this.ClearMessage();

            var result = _employeeService.GetAllEmployees(x => x.EmployeeCode == searchBy ||
                                                               x.FirstName.Contains(searchBy) ||
                                                               x.LastName.Contains(searchBy) ||
                                                               x.Type.Contains(searchBy) ||
                                                               x.IdNumber == searchBy ||
                                                               x.HireDate == DateTime.Parse(searchBy));

            this.LoadGrid(result);
        }

        protected void btnSearchClear_Click(object sender, EventArgs e)
        {
            this.ClearMessage();
            txtSearch.Text = string.Empty;
            this.LoadGrid();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            lblEmployeeForm.Text = "Add Employee";
            EmployeeFormModalPopupExtender.Show();
        }

        protected void btnEmployeeFormClose_Click(object sender, EventArgs e)
        {
            lblEmployeeForm.Text = string.Empty;
            EmployeeFormModalPopupExtender.Hide();
            ucEmployeeForm.ClearForm();
            EmployeeGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < EmployeeGridView.Rows.Count; i++)
            {
                GridViewRow row = EmployeeGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    // TODO: Check relationships before delete

                    string code = (string)this.EmployeeGridView.DataKeys[i].Value;
                    results.Add(_employeeService.DeleteEmployee(code));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                this.ShowMessage("Please select records for deletion and try again.", SiteMaster.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                this.ShowMessage(succesMessages, SiteMaster.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                this.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " record(s) was not deleted.", SiteMaster.MessageType.Error);

            EmployeeGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnEmployeeDetailsClose_Click(object sender, EventArgs e)
        {
            ucEmployeeDetail.ClearDetail();
            EmployeeDetailModalPopupExtender.Hide();
        }

        #endregion

        #region GridView Methods
        
        protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.ClearMessage();
            lblEmployeeForm.Text = "Edit Employee";
            string primaryKey = EmployeeGridView.DataKeys[e.NewEditIndex].Value.ToString();
            ucEmployeeForm.LoadForm(primaryKey);
            EmployeeFormModalPopupExtender.Show();
        }

        protected void EmployeeGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            this.ClearMessage();
            string primaryKey = EmployeeGridView.DataKeys[e.NewSelectedIndex].Value.ToString();
            ucEmployeeDetail.LoadDetail(primaryKey);
            EmployeeDetailModalPopupExtender.Show();
        }

        protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            EmployeeGridView.PageIndex = e.NewPageIndex;
            EmployeeGridView.EditIndex = -1;

            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            EmployeeGridView.DataSource = _employeeService.GetAllEmployees();
            EmployeeGridView.DataBind();
        }

        private void LoadGrid(IList<Employee> entities)
        {
            EmployeeGridView.DataSource = entities;
            EmployeeGridView.DataBind();
        }

        private void ShowMessage(string message, AGR.Web.SiteMaster.MessageType messagetype)
        {
            SiteMaster master = (SiteMaster)Page.Master;
            master.ShowMessage(message, messagetype);
        }

        private void ClearMessage()
        {
            SiteMaster master = (SiteMaster)Page.Master;
            master.ClearMessage();
        }

        #endregion
    }
}